//
//  WH_OrderSViewController.m
//  App_6.23
//
//  Created by wanghao on 16/8/8.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_OrderSViewController.h"
#import <ZYQAssetPickerController.h>
#import "WH_Home.h"

#define ScreenHeight    [[UIScreen mainScreen] bounds].size.height
#define ScreenWidth     [[UIScreen mainScreen] bounds].size.width


@interface WH_OrderSViewController ()<ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>
{
    UIView               *_editv;
    UITextView           *_textView;
    UILabel              *_placeholderLabel;
    UIButton             *_addPic;
}
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) NSMutableArray *urlArray;

@end

@implementation WH_OrderSViewController

-(void)viewWillAppear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _imageArray = [NSMutableArray array];
    _urlArray = [NSMutableArray array];
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStyleDone target:self action:@selector(shareListAction)];
    UIImageView *imageProduct = [[UIImageView alloc] initWithFrame:CGRectMake(15, 15, 70, 70)];
    [imageProduct sd_setImageWithURL:[NSURL URLWithString:_peroid.product_image] placeholderImage:PLACEHOLDER_CELL_SAME];
    [self.view addSubview:imageProduct];
    //
    UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(imageProduct.frame.size.width + 10, imageProduct.frame.origin.y + 10, SCREEN_WIDTH -(imageProduct.frame.size.width + 10) - 10, 20)];
    productLabel.font = [UIFont systemFontOfSize:15.f];
    productLabel.text = _peroid.product_name;
    [self.view addSubview:productLabel];
    //
    UILabel *preiodLabel = [[UILabel alloc] initWithFrame:CGRectMake(imageProduct.frame.size.width + 10, productLabel.frame.origin.y + 10 + productLabel.frame.size.height, SCREEN_WIDTH -(imageProduct.frame.size.width + 10) - 10, 20)];
    preiodLabel.text = [NSString stringWithFormat:@"期  号:  %@", _peroid.product_period_no];
    preiodLabel.font = [UIFont systemFontOfSize:15.f];
    [self.view addSubview:preiodLabel];
    // 评论 + 照片
    _editv = [[UIView alloc] initWithFrame:CGRectMake(15, 110, ScreenWidth-15*2, 0)];
    _editv.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    [self.view addSubview:_editv];
    
    // 评论 UITextView
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 15, CGRectGetWidth(_editv.frame)-15*2, 70*WID_ONE)];
    _textView.backgroundColor = [UIColor whiteColor];
    _textView.delegate = self;
    [_editv addSubview:_textView];
    
    // 提示字
    _placeholderLabel = [[UILabel alloc] init];
    _placeholderLabel.frame =CGRectMake(5, 6, CGRectGetWidth(_editv.frame)-15*4, 20);
    _placeholderLabel.text = @"在此编辑您的分享内容!";
    _placeholderLabel.textColor = [UIColor colorWithWhite:0.4 alpha:0.6];
    _placeholderLabel.font = [UIFont systemFontOfSize:12.0];
    _placeholderLabel.enabled = NO; // lable必须设置为不可用
    _placeholderLabel.backgroundColor = [UIColor clearColor];
    [_textView addSubview:_placeholderLabel];
    
    // + pic
    _addPic = [UIButton buttonWithType:UIButtonTypeCustom];
    _addPic.frame = CGRectMake(15, CGRectGetMaxY(_textView.frame)+15, 70*WID_ONE, 70*WID_ONE);
    [_addPic setImage:[UIImage imageNamed:@"addImage.png"] forState:UIControlStateNormal];
    [_addPic addTarget:self action:@selector(addPicEvent) forControlEvents:UIControlEventTouchUpInside];
    [_editv addSubview:_addPic];
    _editv.frame = CGRectMake(15, 110, ScreenWidth-15*2, CGRectGetMaxY(_addPic.frame)+20);
}

#pragma mark - 发布晒单

- (void)shareListAction{
    
    [self loadImage];

}

#pragma mark - 上传图片

-(void)upImage
{
    NSLog(@"_textView=== %@",_textView.text);
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    
    [para setObject:@"share_add" forKey:@"action"];
    [para setObject:NSUSERID forKey:@"user_id"];
    [para setObject:_peroid.product_period forKey:@"product_period"];
    [para setObject:_urlArray forKey:@"img_array"];
    [para setObject:_textView.text forKey:@"content"];

    [WH_AppTools postUrl:URLstr body:para result:HXJSON requestStyle:HXRequestDic headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        if ([status isEqualToString:@"success"]) {
            
            [WSProgressHUD showImage:nil status:status maskType:WSProgressHUDMaskTypeClear];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];

            });

        }else{
            
            [WSProgressHUD showImage:nil status:message maskType:WSProgressHUDMaskTypeClear];
        }


    } failure:^(NSError *error) {
        
        
    }];
    
}

#pragma mark - 图片Url

- (void)loadImage{
    
    NSMutableArray *imageUrl = [NSMutableArray array];
    for (UIImage *imageV in _imageArray) {
        
        NSData *data = UIImageJPEGRepresentation(imageV, 0.8);
        NSString *image64 = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSString *imageStr = [NSString stringWithFormat:@"jpg;base64,%@",image64];
        [imageUrl addObject:imageStr];

    }

    NSLog(@"%ld=======",(unsigned long)imageUrl.count);
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    
    [para setObject:@"share_upload_img" forKey:@"action"];
    [para setObject:NSUSERID forKey:@"user_id"];
    [para setObject:imageUrl forKey:@"file_data"];
    
    [WH_AppTools postUrl:URLstr body:para result:HXJSON requestStyle:HXRequestDic headerFile:nil success:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSString *status = [dic objectForKey:@"status"];
        NSString *message = [dic objectForKey:@"message"];
        NSArray *imgArr = [dic objectForKey:@"img_array"];

        if ([status isEqualToString:@"success"]) {
            for (NSDictionary *dic in imgArr) {
                
                NSString *url = [dic objectForKey:@"url"];
                [_urlArray addObject:url];
            }
            [self upImage];
        }else{
            
            [WSProgressHUD showImage:nil status:message maskType:WSProgressHUDMaskTypeClear];
        }
        
        
    } failure:^(NSError *error) {
        
        
    }];

}
#pragma mark - UIbutton event

- (void)addPicEvent
{

    if (_imageArray.count >= 3) {
        [WSProgressHUD showImage:nil status:@"最多只能上传3张图片" maskType:WSProgressHUDMaskTypeClear];
    } else {
        [self selectPictures];
    }
}

// 本地相册选择多张照片
- (void)selectPictures
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 3 - _imageArray.count;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
                              {
                                  if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo])
                                  {
                                      NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                                      
                                      return duration >= 5;
                                  } else {
                                      return YES;
                                  }
                              }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}

// 图片布局
- (void)nineGrid
{
    for (UIImageView *imgv in _editv.subviews)
    {
        if ([imgv isKindOfClass:[UIImageView class]]) {
            [imgv removeFromSuperview];
        }
    }
    
    CGFloat width = 70*WID_ONE;
    CGFloat widthSpace = (ScreenWidth - 15*4 - 70*WID_ONE*4) / 3.0;
    CGFloat heightSpace = 10*WID_ONE;
    
    NSInteger count = _imageArray.count;
    _imageArray.count > 3 ? (count = 3) : (count = _imageArray.count);
    
    for (int i=0; i<count; i++)
    {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(15+(width+widthSpace)*(i%4), (i/4)*(width+heightSpace) + CGRectGetMaxY(_textView.frame)+15, width, width)];
        imgv.image = _imageArray[i];
        imgv.userInteractionEnabled = YES;
        [_editv addSubview:imgv];
        
        UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
        delete.frame = CGRectMake(width-16, 0, 16*WID_ONE, 16*WID_ONE);
        [delete setBackgroundImage:[UIImage imageNamed:@"X"] forState:UIControlStateNormal];
        [delete addTarget:self action:@selector(deleteEvent:) forControlEvents:UIControlEventTouchUpInside];
        delete.tag = 10+i;
        [imgv addSubview:delete];
        
        if (i == _imageArray.count - 1)
        {
            if (_imageArray.count % 4 == 0) {
                _addPic.frame = CGRectMake(15, CGRectGetMaxY(imgv.frame) + heightSpace, 70*WID_ONE, 70*WID_ONE);
            } else {
                _addPic.frame = CGRectMake(CGRectGetMaxX(imgv.frame) + widthSpace, CGRectGetMinY(imgv.frame),  70*WID_ONE,  70*WID_ONE);
            }
            
            _editv.frame = CGRectMake(15, 110, ScreenWidth-15*2, CGRectGetMaxY(_addPic.frame)+20);
        }
    }
}

// 删除照片
- (void)deleteEvent:(UIButton *)sender
{
    UIButton *btn = (UIButton *)sender;
    [_imageArray removeObjectAtIndex:btn.tag-10];
    
    [self nineGrid];
    
    if (_imageArray.count == 0)
    {
        _addPic.frame = CGRectMake(15, CGRectGetMaxY(_textView.frame)+15, 70*WID_ONE,  70*WID_ONE);
        _editv.frame = CGRectMake(15, 110, ScreenWidth-15*2, CGRectGetMaxY(_addPic.frame)+20);
    }
}

#pragma mark - ZYQAssetPickerController Delegate

- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       for (int i=0; i<assets.count; i++)
                       {
                           ALAsset *asset = assets[i];
                           UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
                           [_imageArray addObject:tempImg];
                           NSLog(@"上传%ld张图片",_imageArray.count);
                           
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [self nineGrid];
                               
                           });
                       }
                   });
}

#pragma makr - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 0) {
        _placeholderLabel.text = @"在此编辑您的分享内容!";
    } else {
        _placeholderLabel.text = @"";
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
